package com.abel.bigwater.dataserver.model.ewide

import com.abel.bigwater.data.BcdString
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.serializer.SerializerFeature
import io.netty.buffer.Unpooled
import org.joda.time.DateTime
import org.junit.Assert
import org.junit.Test
import org.slf4j.LoggerFactory

class TermBurstDataTest {

    @Test
    fun parseBuf() {
        val buf = Unpooled.buffer().apply { writeBytes(BcdString.toByteArray("8220130721200129000000")) }
        val d = TermBurstData()
        assert(d.parseBuf(buf))

        lgr.info(JSON.toJSONStringWithDateFormat(d, JSON.DEFFAULT_DATE_FORMAT, SerializerFeature.PrettyFormat))
        Assert.assertEquals(DateTime(2013, 7, 21, 20, 1, 29).toDate(), d.startTime)

        Assert.assertFalse(d.deviceStatus!!.readMutant24)
    }

    @Test
    fun pack() {
        val d = TermBurstData().apply {
            startTime = DateTime(2013, 7, 21, 20, 1, 29).toDate()
            deviceStatus = DeviceStatus()
        }

        val buf = Unpooled.buffer().apply {
            d.pack(this)
        }

        Assert.assertEquals(11, buf.readableBytes())
        Assert.assertEquals("8220130721200129000000", BcdString.hexString(buf))
    }

    @Test
    fun parseWhole() {
        val buf = Unpooled.buffer().apply { writeBytes(BcdString.toByteArray(DEMO_BURST)) }
        val p = KmingPacket()
        Assert.assertTrue(p.parseBuf(buf))

        lgr.info(JSON.toJSONStringWithDateFormat(p, JSON.DEFFAULT_DATE_FORMAT, SerializerFeature.PrettyFormat))

        Assert.assertEquals(TermCodeType().apply {
            manuId = BcdString.fromBcdString("03")
            codeBcd = BcdString.fromBcdString("01000000")
        }, p.termCode)

        val d = p.data as TermBurstData
        Assert.assertEquals(DateTime(2013, 7, 21, 20, 1, 29).toDate(), d.startTime)

        Assert.assertFalse(d.deviceStatus!!.readMutant24)
    }

    @Test
    fun packWhole() {
        val p = KmingPacket().apply {
            termCode = TermCodeType().also {
                it.manuId = BcdString.fromBcdString("03")
                it.codeBcd = BcdString.fromBcdString("01000000")
            }

            deviceStatus = DeviceStatus().also {
                it.lowBattery10 = true
                it.magnet21 = true
                it.breakLine30 = true
            }

            frameNo = 1
            data = TermBurstData().apply {
                startTime = DateTime(2013, 7, 21, 20, 1, 29).toDate()
                deviceStatus = DeviceStatus()
            }
        }

        val buf = Unpooled.buffer().apply {
            p.pack(this)

            Assert.assertEquals(DEMO_BURST, BcdString.hexString(this).toUpperCase())
        }
    }

    companion object {
        const val DEMO_BURST = "5A55010000000301020101000B008220130721200129000000119C6A69"
        private val lgr = LoggerFactory.getLogger(TermBurstDataTest::class.java)
    }
}